package com.ipartek.formacion.url;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class ParsearHTML {

	static Logger log;
	static PrintWriter bw = null;
	static BufferedReader br = null;
	static File archivoHTML = null;

	/**
	 * 
	 */
	public ParsearHTML() {
		super();
		log = Logger.getLogger(this.getClass().getName());
	}

	public static void main(String[] args) {
		PropertyConfigurator.configure("config/log4j.properties");

		ParsearHTML html = new ParsearHTML();

		URL aURL = null;
		String inputLine;

		try {
			aURL = new URL("http://ibaworldtour.com");
			System.out.println("protocol = " + aURL.getProtocol());
			System.out.println("host = " + aURL.getHost());
			System.out.println("filename = " + aURL.getFile());
			System.out.println("port = " + aURL.getPort());
			System.out.println("ref = " + aURL.getRef());

			archivoHTML = new File("temp/ibaworldtour.html");
			// Date fecha1 = new Date();

			/*
			 * if (archivoHTML.exists()) {
			 * 
			 * }
			 */
			br = new BufferedReader(new InputStreamReader(aURL.openStream()));

			bw = new PrintWriter(new FileWriter("temp/ibaworldtour.html"));
			while ((inputLine = br.readLine()) != null) {
				bw.println(inputLine);
				bw.flush();
			}
			log.info("El fichero temp/ibaworldtour.html ya esta creado");

		} catch (MalformedURLException e) {
			html.log.error("[MalformedURLException] " + e.getMessage());
		} catch (FileNotFoundException e) {
			// System.out.println("No encuentra el fichero: ");
			html.log.error("[FileNotFoundException] " + e.getMessage());
		} catch (IOException e) {
			// System.out.println("IOException");
			html.log.error("[IOException] " + e.getMessage());
		} catch (Exception e) {
			html.log.error("[Exception] " + e.getMessage());
		} finally {
			try {
				if (bw != null) {
					bw.close();
				}

				if (br != null) {
					br.close();
				}

			} catch (IOException e) {
				html.log.error("[IOException] " + e.getMessage());
			}

		}
	}
}
